var paginationTotal = 20;//记录总数
var isSearch = false;
var browseType = 'fold';    //浏览<{$lang.type}>
var isReload=false;
function search(val){
	if(val != undefined){
		$('#shipping_method_sch').val(val);
	}
	isSearch = true;
	paginationCurrentPage=1;
	initData(0);
}
function shiptype_search(val,obj){
	//$(".shiptype a").removeClass('sel');	
	//$(obj).addClass('sel');
	search(val);
}

function loadData(page, pageSize) {
    var vForm = {};
    if (isSearch == true && isSearch != undefined) {
        vForm = $("#sForm").serialize();
        vForm+='&browsetype='+browseType;
    }
    vForm.browsetype = browseType;
    loading();
    $.ajax({
        type: "POST",
        async: false,
        dataType: "json",
        url: "/order/assign/list/page/" + page + "/pageSize/" + pageSize,
        data: vForm,
        success: function(json) {
            closeLoading();
            var list = "";
            var trclass="";
            paginationTotal = json.count;
			var i = (page == 1 ? 1 : pageSize * (page - 1) + 1);
            if (json.ask == 0) {
                list = "<td colspan='13' class=\"center\">&nbsp;<{$lang.no_data}></td>";
            } else {
                //var i = page==1 ? 1 : pageSize * (page-1)+1;
                $.each(json.result, function(key, val) {
                    if ((key + 1) % 2 == 1 ) {
                        trclass='';
                    } else {
                        trclass='even-tr';
                    }
                    if(browseType!='fold'){trclass='';}
                    list += "<tr class="+trclass+">";
                    list += "<td><input type='checkbox' value='" + val.order_id + "' id='orderids_" + val.order_id + "' name='orderids[]'></td>";
					list += '<td>'+(key+1)+'</td>';
                    list += "<td><a href=\"javascript:detail('" + val.orders_code + "')\">" + val.orders_code + "</a></td>";
                    list += "<td>" + val.customer_order_code + "</td>";
                    list += "<td>" + val.customer_id + "</td>";
                    list += "<td>" + val.consignee_country_id + "</td>";
                    list += "<td>" + val.shipping_method + "</td>";
                    list += "<td>" + val.add_time + "</td>";
                    list += "<td>" + val.print_time + "</td>";
                    list += "<td>" + val.order_print_id + "</td>";
                    list += "<td>" + val.pickup_user_name + "</td>";
                    list += "<td>" + val.orders_status+"/"+val.process_status_ch + "</td>";
                    list += "<td>" ;
					
                    list += "<a href='javascript:;' onclick='assign("+val.order_id+",\""+val.orders_code+"\","+val.process_status+");'>" +	"<img src='/images/icon/edit.gif' title='分配'></a>" ;
					
                    list += "</td>";
                    list += "</tr>";
                    if (val.order_product != null && val.order_product !='') {
                        list += "<tr><td colspan='13' style='padding:0;'>";
                        $.each(val.order_product, function(key, value) {
                            list += "<table width=100% border=0 cellspacing=0 cellpadding=0><tr class='even-tr'>";
                            list+="<td width='8%'>&nbsp;</td>";
//                            list += "<td width='20%'><{$lang.sku}>:<a href=\"javascript:proDetails('" + value.op_id + "')\">" + val.customer_id+"-"+value.product_sku + "</a></td>";
                            list += "<td width='20%'><{$lang.sku}>:" + val.customer_id+"-"+value.product_sku + "</td>";
                             list += "<td width='10%'><{$lang.quantity}>:" + value.op_quantity + "</td>";
                            list += "<td width='20%'><{$lang.category}>:" + value.category + "</td>";
                            list += "<td><{$lang.ws_code}>:" + value.ws_code + "</td>";
                            list += "</tr></table>";
                        });
                        list += "</td></tr>";
                    }
                });
            }
            $("#loadData").html(list);
        }
    });
}

$(function() {
//    initData(0);
    $("[name=ckAll]").click(function() {
        if ($(this).is(':checked')) {
            $("[name='orderids[]']").attr('checked', true);
        } else {
            $("[name='orderids[]']").attr('checked', false);
        }
    });

    $('#order_form').dialog({
        autoOpen: false,
        width: 800,
        modal: true,
        show:"slide",
        buttons: {
            '<{$lang.ok}>': function() {
                submitOrder();
            },
            '<{$lang.cancel}>': function() {
                $(this).dialog('close');
            }
        },
        close: function() {
            $('#orderForm')[0].reset();
        }
    });
	
	//<{$lang.batch}>分配
	$("#right_confirm_batch").dialog({
	     autoOpen : false,
		modal : true,
		height : 'auto',
		show : "slide",
		buttons : {
			'<{$lang.ok}>' : function() {
			    var pickuser=$("#batchpickusers").val();
				if(pickuser==""){
				   alert("<{$lang.pls}><{$lang.pickup_user}>!");
				   return;
				}
				var vForm = {};
				vForm = $("#assignBatchForm").serializeArray();
			
				$('#message').text("");
				//loading();
				$.ajax({ // 这里使用到Jquery的ajax<{$lang.method}>
					type : "POST",
					async : false,
					dataType : "json",
					url : "/order/assign/batchassignpickuser", // 请求的处理url
					data : vForm,
					success : function(json) {
						closeLoading();
						if (json.ask == 1) {// <{$lang.operation}><{$lang.success}>
							$('#alert_msg p').html("<{$lang.operation}><{$lang.success}>");
							$('#alert_msg').dialog('open');
							loadData(paginationCurrentPage, paginationPageSize);
						} else {
							$('#alert_msg p').text("<{$lang.operation}><{$lang.fail}>  :"+json.msg);
							$('#alert_msg').dialog('open');
						}
					}
				});
				$(this).dialog('close');
			},
			'<{$lang.cancel}>' : function() {
				$(this).dialog('close');
			}
		}
	}
	);
	
	
    // 分配
	$("#right_confirm").dialog({
		autoOpen : false,
		modal : true,
		height : 'auto',
		show : "slide",
		buttons : {
			'<{$lang.ok}>' : function() {
			   var pickuser=$("#pickusers").val();
				if(pickuser==""){
				   alert("<{$lang.pls}><{$lang.pickup_user}>!");
				   return;
				}
				$('#message').text("");
				//loading();
				var vForm = {};
				vForm = $("#assignForm").serializeArray();
				$.ajax({ // 这里使用到Jquery的ajax<{$lang.method}>
					type : "POST",
					async : false,
					dataType : "json",
					url : "/order/assign/assignpickuser", // 请求的处理url
					data : vForm,
					success : function(json) {
						closeLoading();
						if (json.ask == 1) {// <{$lang.operation}><{$lang.success}>
							$('#alert_msg p').html("<{$lang.operation}><{$lang.success}>");
							$('#alert_msg').dialog('open');
							loadData(paginationCurrentPage, paginationPageSize);
						} else {
							$('#alert_msg p').text("<{$lang.operation}><{$lang.fail}>  :"+json.msg);
							$('#alert_msg').dialog('open');
						}
					}
				});
				$(this).dialog('close');
			},
			'<{$lang.cancel}>' : function() {
				$(this).dialog('close');
			}
		}
	});
	
	// 弹出<{$lang.tip}>
	$("#alert_msg").dialog({
		autoOpen : false,
		modal : true,
		width : 400,
		show : "slide",
		buttons : {
			'<{$lang.close}>' : function() {
				$(this).dialog('close');
			}
		}

	});
	//回车处理
	$("#code").add("#customerId").keyup(function(e){
		var key = e.which;
		if(key==13){
			search();
		}
	});
});

//<{$lang.operation}><{$lang.tip}>
function alertTip(tip) {
    $('<div title="<{$lang.tip}>"><p align="center">' + tip + '</p></div>').dialog({
        modal: true,
        buttons: {
            '<{$lang.ok}>': function() {
                $(this).dialog("close");
            }
        }
    });
}
//<{$lang.order}><{$lang.detail}>
function detail(orders_code) {
    var url = '/order/order/detail/orders_code/' + orders_code;
    window.open(url);
}
//浏览风格
function swichBrowseType(vSelf) {
    if (browseType == 'fold') {
        browseType = 'unfold';
        $(vSelf).val('<{$lang.folder}><{$lang.product}>');
    } else {
        browseType = 'fold';
        $(vSelf).val('<{$lang.folder}><{$lang.product}>');
    }
    initData(paginationCurrentPage - 1, paginationPageSize);
}
//<{$lang.product}><{$lang.detail}>

function proDetails(id) {
    if (isNaN(id) || !id) {
        return false;
    }
    var url = '/order/order/prodetail/id/' + id;
    window.parent.$('<iframe id="ifr_order_product_detail" name="ifr_order_product_detail" src="' + url + '" />').dialog({
        title: '<{$lang.order}><{$lang.product}><{$lang.detail}><{$lang.msg}>',
        autoOpen: true,
        width: 900,
        modal: false,
        resizable: false,
        position:'top',
        autoResize: true,
        close:function() {
            $(this).remove();
            if (isReload) {
                window.location.reload();
                isReload = false;
            }
        },
        buttons: {
            'Close/<{$lang.close}>': function() {
                $(this).remove();
            }
        }
    }).width(875);
}

//<{$lang.add}><{$lang.order}>
function addOrder() {
    changeStep('base');
    $('#orderForm')[0].reset();
    $('.orderError').text('').hide();
    $("#order_form").dialog('open');
}
//<{$lang.add}><{$lang.order}>
function submitOrder() {
    jQuery.post('/order/order/create', $('#orderForm').serialize(), submitOrderBack, 'json');
}
function submitOrderBack(data) {
    if (data == null) return;
    if (data.ask == '0') {
        $('.orderError', '#order_form').html('<p>' + data.msg.toString() + '</p>').show();
    } else {
        $("#order_form").dialog('close');
        $('<div title="<{$lang.tip}>"><p><{$lang.congratulation}>，<{$lang.add}><{$lang.order}><{$lang.success}></p></div>').dialog({
            modal: true,
            buttons: {
                '<{$lang.ok}>': function() {
                    $(this).dialog("close");
                    window.open('/order/order/detail/orders_code/' + data.orders_code, '', '');
                }
            }
        });
    }
}

//检查<{$lang.customer_code}>
function checkCustomer(Cid) {
    if(Cid==''){return;}
    $.ajax({
        type: "post",
        async: false,
        dataType: "json",
        url: "/customer/customer/check",
        data:{
            'customer_name':Cid
        },
        success: function(json) {
            if (json.ask == '0') {
                $('.orderError', '#order_form').html('<p><{$lang.customer}><{$lang.can_not_use_warehouse}></p>').show();
            }
        }
    });
}

function changeStep(id) {
    var msg = '';
    if (id == 'customer') {
        var customer_id = $('#customer_id').val();
        if (customer_id == '') {
            msg = '<{$lang.pls_input}><{$lang.customer_code}>';
        } else {
            checkCustomer(customer_id);
        }
    } else if (id == 'addProduct') {
        var pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
        /*if($('#order_user_email').val()=='' ||  pattern.test($('#order_user_email').val())==false){
         msg = '<{$lang.pls_input}><{$lang.email}><{$lang.or}><{$lang.wrong}>';
         }else if($('select#shipping_method').val()==''){
         msg = '<{$lang.pls}><{$lang.shipping_method}>';
         }
         */
        /*
         var len = $(':hidden[name="p_ids[]"]').length;
         if(len==0 || len=='' || len==undefined){
         msg = '<{$lang.pls}><{$lang.product}>...';
         }
         */
    }
    if (msg != '') {
        $('.orderError', '#order_form').html('<p>' + msg + '</p>').show();
    } else {
        $("#base").hide();
        $("#addProduct").hide();
        $("#customer").hide();
        $("#" + id).show();
        $('.orderError', '#order_form').html('').hide();
    }
}
function batchassign(){
       var orders = "";
	   var isSelOrder=false;
		$("[name=orderids[]]:checked").each(function(){
			orders+='<input type="hidden"   value="'+$(this).val()+'" name="select_orders[]">';
			isSelOrder=true;
		});
		if(!isSelOrder){
		   alert("<{$lang.pls}><{$lang.order}>");
		   return;
		}
		$("#assignOrders").html(orders);
		$("#right_confirm_batch").dialog('open');
       
}

function assign(order_id,ws_code,process_status){
	Uorder_code = ws_code;
	$("#order_code").val(ws_code);
	//var text = process_status==1?("<{$lang.order}> "+ws_code+" 分配给"):("<{$lang.order}>:["+ws_code+"] <{$lang.ok}>后即将分配给所选<{$lang.pickup_user}>");
	$("#right_confirm p").html("<{$lang.order}>:["+ws_code+"]");
	$("#right_confirm").dialog('open');
}